package com.springboot.springtest.Controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.springtest.Pojo.User;
import com.springboot.springtest.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

/**
 * @author wwj
 * @date 2021/3/11 0011 15:08
 */
@Controller
@RequestMapping(value = "/User")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/list")
    public String getList(Model model,Integer pageNum,Integer pageSize,User user){
        //为了程序的严谨性，判断非空：
        if(pageNum == null){
            pageNum = 1;   //设置默认当前页
        }
        if(pageNum <= 0){
            pageNum = 1;
        }
        if(pageSize == null){
            pageSize = 5;    //设置默认每页显示的数据数
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum,pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<User> userList = userService.queryAll(user);
            System.out.println("分页数据："+userList);
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<User> pageInfo = new PageInfo<User>(userList,pageSize);
            //4.使用model/map/modelandview等带回前端
            model.addAttribute("pageInfo",pageInfo);
        }finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "user/user_list";
    }

    @RequestMapping (value = "/GoaddPage")
    public String GoaddPage(){

        return "user/user_add";
    }
    @RequestMapping (value = "/GoeditPage")
    public String GoeditPage(Model model, String id){
        User user=userService.queryById(id);
        model.addAttribute("user",user);
        return "user/user_edit";
    }
    @RequestMapping(value = "/updateUser")
    public String updatUser(User user){
        userService.update(user);
        return "redirect:/User/list";
    }

    @RequestMapping(value = "/deleteUser")
    public String deleteUser(String id){
        userService.deleteById(id);
        return "redirect:/User/list";
    }
    @RequestMapping(value = "/addUser")
    public String saveUser(User user){
        userService.insert(user);
        return "redirect:/User/list";
    }
}
